package com.dliyun.fort.gateway.ssh;

import com.jcraft.jsch.ChannelShell;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.InputStream;
import java.util.Arrays;

/**
 * @author jtoms.shen
 * @version 1.0
 * @date 2019/3/21 14:18
 */
@Slf4j
public class ShellOutPutTask extends Thread {
    private final Session session;

    public ShellOutPutTask(Session session) {
        this.session = session;
    }

    @Override
    public void run() {
        byte[] buffer = new byte[1024];

        try {

            SSHClient client = SessionStorage.get(session.getId());

            ChannelShell channel = client.getChannel();
            InputStream inputStream = channel.getInputStream();

            //循环读取
            int i = 0;
            //如果没有数据来，线程会一直阻塞在这个地方等待数据。
            while ((i = inputStream.read(buffer)) != -1) {
                String data = new String(Arrays.copyOfRange(buffer, 0, i));
                SessionStorage.sendMessage(session, MessageResponse.Code.xterm, data);
            }

            if (client.getSession().isConnected()) {
                this.session.close();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

